from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse


class MyMiddleware(MiddlewareMixin):

    def process_request(self, request):
        print("\033[31m爱意东升西洛，浪漫至死不渝\033[0m")

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("\033[32m相濡以沫，醉一场红尘恋\033[0m")

    def process_response(self, request, response):
        print("\033[33m余生是你，满心欢喜\033[0m")

        return response


class MyMiddleware2(MiddlewareMixin):

    def process_request(self, request):
        print("\033[31m爱意东升西洛，浪漫至死不渝\033[0m")

    def process_view(self, request, callback, callback_args, callback_kwargs):
        print("\033[32m相濡以沫，醉一场红尘恋\033[0m")

    def process_response(self, request, response):
        print("\033[33m余生是你，满心欢喜\033[0m")

        return response


class VisitLimit(MiddlewareMixin):
    visit_times = {}  # 访问次数字典

    def process_request(self, request):
        ip_addr = request.META['REMOTE_ADDR']
        path_url = request.path_info

        if not path_url.startswith("/test"):
            return None

        times = self.visit_times.get(ip_addr, 0)
        self.visit_times[ip_addr] = times + 1

        if self.visit_times.get(ip_addr) <= 5:
            return

        return HttpResponse(f"访问频繁")

